import qs from 'qs'

/**
 * 转换url参数
 * @deprecated GET 请求时使用 axios 自带转换参数
 * @param url
 * @param params
 * @returns {string}
 */
export function createUrlParams (url, params) {
  const hasWen = url.indexOf('?') > -1 ? '' : '?'
  const result = []

  for (const key of Object.keys(params)) {
    const value = params[key]
    if (value !== undefined) {
      result.push(`${key}=${value}`)
    }
  }

  return result.length ? `${url}${hasWen}${result.join('&')}` : url
}

/**
 * 添加搜索前缀
 * @param params
 * @param prefix
 */
export function addSearchParamsPrefix (params = {}, prefix = 's_') {
  const result = {}
  for (const key of Object.keys(params)) {
    result[`${prefix}${key}`] = params[key]
  }

  return result
}

/**
 * FormData Interceptor
 * @param config
 * @param options
 * @returns {*}
 */
export function requestFormDataInterceptor (config, options) {
  if (options.useFormData) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  } else {
    config.headers['Content-Type'] = 'application/json; charset=UTF-8'
  }

  return config
}

/**
 * FormData transform
 * @param data
 * @param options
 * @returns {string|*|string}
 */
export function requestFormDataTransform (data, options) {
  if (!data || typeof data === 'string') return data

  if (!options.useFormData) return JSON.stringify(data)
  const res = qs.stringify(data, { encodeValuesOnly: true }).replace(/\[([_|a-z|A-Z]*)\]/g, '.$1')
  return res
}

/**
 * 南大先腾特有的数据结构
 * @param res
 * @returns {*}
 */
export function responseTransform (res) {
  // IE浏览器不能正确返回
/*
if (typeof res === 'string') {
    try {
      res = JSON.parse(res)
    } catch (error) {

    }
  }

  if (!res || isValue(res)) return res

  const { data, code, message } = res

  if (code && code !== 0) {
    const error = new Error(message)
    error.code = code
    error.data = data
    throw error
  }

  return data === undefined ? res : data
  */
  return res
}

/**
 * isValue
 * @param value
 * @returns {boolean}
 */
function isValue (value) {
  if (value === null || value === undefined) return true

  if (value instanceof Date) return true

  return ['string', 'number', 'boolean'].includes(typeof value)
}
